from flask import Blueprint, jsonify, request
from app.models.Skillc2 import News, User
from app import db
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime
from sqlalchemy import or_, and_

news_bp = Blueprint('news', __name__)

@news_bp.route('/news', methods=['GET'])
def get_news_list():
    """获取新闻列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        category = request.args.get('category')
        tag = request.args.get('tag')
        keyword = request.args.get('keyword')
        sort_by = request.args.get('sort_by', 'create_time')  # create_time, view_count, like_count
        order = request.args.get('order', 'desc')  # asc, desc
        
        # 构建查询
        query = News.query
        
        # 只显示已发布的新闻
        query = query.filter_by(IsPublished=True)
        
        # 分类过滤
        if category:
            query = query.filter_by(Category=category)
        
        # 标签过滤
        if tag:
            query = query.filter(News.Tags.like(f'%{tag}%'))
        
        # 关键词搜索（标题和内容）
        if keyword:
            query = query.filter(
                or_(
                    News.Title.like(f'%{keyword}%'),
                    News.Content.like(f'%{keyword}%'),
                    News.Summary.like(f'%{keyword}%')
                )
            )
        
        # 置顶新闻优先
        query = query.order_by(News.IsTop.desc())
        
        # 排序
        sort_column = getattr(News, {
            'create_time': 'CreateTime',
            'view_count': 'ViewCount',
            'like_count': 'LikeCount'
        }.get(sort_by, 'CreateTime'))
        
        if order == 'asc':
            query = query.order_by(sort_column.asc())
        else:
            query = query.order_by(sort_column.desc())
        
        news_list = query.paginate(page=page, per_page=per_page)
        
        return jsonify({
            'status': 'success',
            'data': {
                'items': [news.to_simple_dict() for news in news_list.items],
                'total': news_list.total,
                'pages': news_list.pages,
                'current_page': page,
                'has_next': news_list.has_next,
                'has_prev': news_list.has_prev
            }
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@news_bp.route('/news/hot', methods=['GET'])
def get_hot_news():
    """获取热门新闻"""
    try:
        limit = request.args.get('limit', 5, type=int)
        query = News.query.filter(and_(
            News.IsPublished == True,
            News.IsHot == True
        )).order_by(News.ViewCount.desc())
        hot_news = query.limit(limit).all()
        
        return jsonify({
            'status': 'success',
            'data': [news.to_simple_dict() for news in hot_news]
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@news_bp.route('/news/<int:news_id>', methods=['GET'])
def get_news(news_id):
    """获取新闻详情"""
    try:
        news = News.query.get_or_404(news_id)
        
        if not news.IsPublished:
            return jsonify({
                'status': 'error',
                'message': '该新闻尚未发布'
            }), 404
        
        # 增加浏览次数
        news.ViewCount += 1
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'data': news.to_dict()
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@news_bp.route('/news', methods=['POST'])
@jwt_required()
def create_news():
    """创建新闻"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404
            
        data = request.get_json()
        
        # 验证必要字段
        required_fields = ['title', 'content', 'category']
        if not all(field in data for field in required_fields):
            return jsonify({
                'status': 'error',
                'message': '缺少必要字段'
            }), 400
        
        # 自动生成摘要（如果未提供）
        if not data.get('summary'):
            content = data['content']
            data['summary'] = content[:200] + '...' if len(content) > 200 else content
        
        news = News(
            Title=data['title'],
            Content=data['content'],
            Summary=data['summary'],
            Author=user.UserName,  # 使用当前用户名作为作者
            Category=data['category'],
            Tags=data.get('tags'),
            CoverImage=data.get('cover_image'),
            CoverVideo=data.get('cover_video'),
            CoverRadio=data.get('cover_radio'),
            IsTop=data.get('is_top', False),
            IsPublished=data.get('is_published', True),
            IsHot=data.get('is_hot', False),
            PublishTime=datetime.now() if data.get('is_published', True) else None
        )
        
        db.session.add(news)
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '新闻创建成功',
            'data': news.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@news_bp.route('/news/<int:news_id>', methods=['PUT'])
@jwt_required()
def update_news(news_id):
    """更新新闻"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404
            
        news = News.query.get_or_404(news_id)
        if news.Author != user.UserName:
            return jsonify({
                'status': 'error',
                'message': '只有作者可以修改新闻'
            }), 403
            
        data = request.get_json()
        
        # 更新字段
        if 'title' in data:
            news.Title = data['title']
        if 'content' in data:
            news.Content = data['content']
            # 如果内容更新了，同时更新摘要
            if not data.get('summary'):
                news.Summary = data['content'][:200] + '...' if len(data['content']) > 200 else data['content']
        if 'summary' in data:
            news.Summary = data['summary']
        if 'category' in data:
            news.Category = data['category']
        if 'tags' in data:
            news.Tags = data['tags']
        if 'cover_image' in data:
            news.CoverImage = data['cover_image']
        if 'cover_video' in data:
            news.CoverVideo = data['cover_video']
        if 'cover_radio' in data:
            news.CoverRadio = data['cover_radio']
        if 'is_top' in data:
            news.IsTop = data['is_top']
        if 'is_published' in data:
            news.IsPublished = data['is_published']
            if data['is_published'] and not news.PublishTime:
                news.PublishTime = datetime.now()
        if 'is_hot' in data:
            news.IsHot = data['is_hot']
        
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '新闻更新成功',
            'data': news.to_dict()
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@news_bp.route('/news/<int:news_id>', methods=['DELETE'])
@jwt_required()
def delete_news(news_id):
    """删除新闻"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404
            
        news = News.query.get_or_404(news_id)
        if news.Author != user.UserName:
            return jsonify({
                'status': 'error',
                'message': '只有作者可以删除新闻'
            }), 403
            
        db.session.delete(news)
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '新闻删除成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@news_bp.route('/news/categories', methods=['GET'])
def get_categories():
    """获取新闻分类列表"""
    try:
        categories = db.session.query(News.Category).distinct().all()
        return jsonify({
            'status': 'success',
            'data': [category[0] for category in categories]
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@news_bp.route('/news/tags', methods=['GET'])
def get_tags():
    """获取所有标签列表"""
    try:
        # 获取所有标签并展平
        tags_query = db.session.query(News.Tags).filter(News.Tags != None).distinct().all()
        all_tags = set()
        for tags in tags_query:
            if tags[0]:
                all_tags.update(tags[0].split(','))
        
        return jsonify({
            'status': 'success',
            'data': sorted(list(all_tags))
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@news_bp.route('/news/<int:news_id>/like', methods=['POST'])
@jwt_required()
def like_news(news_id):
    """点赞新闻"""
    try:
        news = News.query.get_or_404(news_id)
        news.LikeCount += 1
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '点赞成功',
            'data': {
                'like_count': news.LikeCount
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500 